package cn.admin.system.staff.domain;

import cn.admin.common.constant.CacheConstants;
import cn.admin.common.domain.LoginUser;
import cn.admin.common.exceptionInterceptor.exception.ServiceException;
import cn.admin.common.redis.RedisCache;
import cn.admin.common.security.context.AuthenticationContextHolder;
import cn.admin.common.utils.StringUtils;
import cn.admin.common.utils.TokenService;
import cn.admin.system.config.client.SysConfigClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

/**
 * @author YJ
 * @DateTime 2023/2/21 16:57
 */
@Service
public class SysLoginService {

    @Autowired
    private SysConfigClient sysConfigClient;

    @Autowired
    private AuthenticationManager authenticationManager;


    @Autowired
    private RedisCache redisCache;

    @Autowired
    private TokenService tokenService;

    public String login(String username,String password ,String code, String uuid){
        //是否需要开启验证码功能
        if (sysConfigClient.captchaEnabled()){
            validateCaptcha(code,uuid);
        }
        //先构造一个未认证的Token
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
        AuthenticationContextHolder.setContext(authenticationToken);
        //该方法会去调用SysUserDetailsServiceImpl.loadUserByUsername
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //获取用户登录信息
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        return tokenService.createToken(loginUser);
    }


    /**
     * 校验验证码
     *
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String code, String uuid) {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            throw new ServiceException(500,"验证码已经过期了");
        }
        if (!code.equalsIgnoreCase(captcha)) {
            throw new ServiceException(500,"验证码错误");
        }
    }

}
